import styles from "./index.module.scss";
import { NavBar, Form, Input, List, Button, Toast } from "antd-mobile";
import { LoginFormType } from "@/types/store";
import { useDispatch } from "react-redux";
import { getCode, login } from "@/store/actions/login";
import { useHistory, useLocation } from "react-router-dom";
import { AxiosError } from "axios";
import { useEffect, useRef, useState } from "react";
import { InputRef } from "antd-mobile/es/components/input";
export default function LoginIndex() {
  const dispatch = useDispatch();
  const history = useHistory();
  const location = useLocation<{ from: string } | undefined>();
  //? 发送验证码===================================================================================================
  // 拿到mobile Input的实例
  const mobileRef = useRef<InputRef>(null);
  // 使用useForm创建form实例绑定到form表单上面
  const [form] = Form.useForm();
  // 倒计时时间
  const [timeLeft, setTimeLeft] = useState(0);
  // 设置一个全局定时器
  const timer = useRef(-1);
  const sendCode = async () => {
    try {
      if (timeLeft > 0) {
        return;
      }
      // 通过form实例的getFieldValue 拿到手机号码
      const mobile = form.getFieldValue("mobile");
      console.log("拿到手机号码", mobile);
      // 通过form实例的getFieldError 拿到手机号的校验提示列表 通过了就没有内容，没通过就有内容，也就是说有长度
      const mobileError = form.getFieldError("mobile").length > 0;
      console.log("拿到手机号码报错提示列表", mobileError);
      // 如果没填手机号码或者手机号码校验错误
      if (!mobile || mobileError) {
        // 让手机号码栏获得焦点并返回
        return mobileRef.current?.focus();
      }
      // dispatch发送验证码请求
      await dispatch(getCode(mobile));
      // 倒计时的值设置为5秒
      setTimeLeft(60);
      // 开启定时器
      //! 这里有个小bug，vscode默认识别这个setInterval是node环境下的定时器，所以有类型限制
      //! 但是我们要的是在浏览器环境下的定时器，类型是number，不是NODEJS.Timer，所以加个window.就行了
      timer.current = window.setInterval(() => {
        setTimeLeft((timeLeft) => timeLeft - 1);
      }, 1000);
    } catch (e) {
      // 这里捕获的错误是60秒内只能发送一次，后端也有限制，60秒内重复发送会报错
      // 这里捕获一下是测试使用，其实可以前端设置好
      const error = e as AxiosError<{ message: string }>;
      console.log(error);

      Toast.show({
        content: error.response?.data.message,
        duration: 1000,
      });
    }
  };
  // 监控时间time为0 的时候清除定时器
  useEffect(() => {
    if (timeLeft === 0) {
      clearInterval(timer.current);
    }
  }, [timeLeft]);
  // 组件销毁的时候，清理定时器
  useEffect(() => {
    return () => {
      clearInterval(timer.current);
    };
  }, []);
  //? 提交登录====================================================================================================
  const submit = async (values: LoginFormType) => {
    console.log("拿到表单数据", values);
    try {
      await dispatch(login(values));
      Toast.show({
        content: "登录成功",
        duration: 1000,
        afterClose: () => {
          // 返回首页
          // history.push("/home");
          const pathname = location.state ? location.state.from : "/home";
          console.log(pathname);

          history.replace(pathname);
        },
      });
    } catch (e) {
      const error = e as AxiosError<{ message: string }>;
      Toast.show({
        content: error.response?.data.message,
        duration: 1000,
      });
    }
  };
  return (
    <div className={styles.root}>
      <NavBar
        children="账号登录"
        style={{
          "--height": "45px",
          "--border-bottom": "1px #eee solid",
          backgroundColor: "#8df",
          color: "#fff",
        }}
        back="返回"
      ></NavBar>

      <div className="login-form">
        <Form
          form={form}
          initialValues={{
            mobile: "13912345678",
            code: "246810",
          }}
          onFinish={submit}
        >
          <Form.Item
            className="login-item"
            name="mobile"
            rules={[
              { required: true, message: "请输入手机号" },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: "手机号格式错误",
              },
            ]}
          >
            <Input ref={mobileRef} maxLength={11} placeholder="请输入手机号" />
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span
                className="code-extra"
                // 判断是否开启定时器，开了的话就去掉这个事件，不给重复点击，没开就绑定事件
                onClick={timeLeft === 0 ? sendCode : undefined}
              >
                {timeLeft === 0 ? "发送验证码" : `${timeLeft}s后重新获取`}
              </span>
            }
          >
            <Form.Item
              name="code"
              className="login-item"
              rules={[
                { required: true, message: "请输入六位验证码" },
                {
                  pattern: /^\d{6}$/,
                  message: "验证码格式错误",
                },
              ]}
            >
              <Input placeholder="请输入验证码" autoComplete="off" />
            </Form.Item>
          </List.Item>

          <Form.Item noStyle>
            <Button block type="submit" color="primary" className="login-submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
